package log

import (
	"fmt"
	"github.com/mitchellh/go-homedir"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"time"
)

var logger *log.Logger
var logFile *os.File
var home, _ = homedir.Dir()
var logPath = fmt.Sprintf("%s/.gitmm", home)
var logfile = fmt.Sprintf("%s/gitmm-%s.log", logPath, time.Now().Format("20060102"))
var logPattern = regexp.MustCompile(`^gitmm-.*\.log$`)
var agingCycle = 7 * 24 * time.Hour

func init() {
	var err error
	os.MkdirAll(logPath, 0750)
	logFile, err = os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640)
	if err != nil {
		fmt.Println("open file.go error :", err)
		return
	}
	logger = log.New(logFile, "", log.LstdFlags)
}

func Printf(format string, v ...any) {
	logger.Printf(format, v...)
}

func Print(v ...any) {
	logger.Print(v...)
}

func Println(v ...any) {
	logger.Println(v...)
}

func FlushAndClose() {
	defer logFile.Close()
}

func AgingLogs() error {
	entries, err := os.ReadDir(logPath)
	if err != nil {
		Printf("failed to read directory: %v", err)
		return err
	}

	now := time.Now()

	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}

		fileName := entry.Name()
		if !logPattern.MatchString(fileName) {
			continue
		}

		info, err := entry.Info()
		if err != nil {
			Printf("failed to get file info: %s, %v", fileName, err)
			continue
		}

		if now.Sub(info.ModTime()) > agingCycle {
			filePath := filepath.Join(logPath, fileName)
			if err := os.Remove(filePath); err != nil {
				Printf("failed to delete file: %s, %v", filePath, err)
			} else {
				Printf("delete file: %v", fileName)
			}
		}
	}
	return nil
}
